package com.fy.fyai.common.ex.handler;

import com.fy.fyai.common.constant.ResultMessageConstant;
import com.fy.fyai.common.ex.BaseException;
import com.fy.fyai.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BaseException.class)
    public R<String> handleBaseException(BaseException e) {
        log.warn("业务异常: {}", e.getMessage());
        return R.no(e.getMessage());
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e) {
        log.error("系统异常", e);
        return R.no(ResultMessageConstant.SYSTEM_ERROR);
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> handleValidationException(MethodArgumentNotValidException e) {
        log.warn("参数校验失败: {}", e.getMessage());
        return R.no(buildErrorMessage(e.getBindingResult()));
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public R<Void> handleBindException(BindException e) {
        log.warn("参数绑定失败: {}", e.getMessage());
        return R.no(buildErrorMessage(e.getBindingResult()));
    }


    /**
     * 处理业务异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public R<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        log.warn("业务异常: {}", e.getMessage());
        return R.no(e.getMessage());
    }

    /**
     * 处理资源未找到异常（如favicon.ico）
     */
    @ExceptionHandler(NoResourceFoundException.class)
    public R<Void> handleNoResourceFoundException(NoResourceFoundException e) {
        // 对于favicon.ico等静态资源缺失，不记录为错误，只记录debug日志
        if (e.getResourcePath() != null && 
            (e.getResourcePath().contains("favicon.ico") || 
             e.getResourcePath().contains("robots.txt"))) {
            log.debug("静态资源未找到: {}", e.getResourcePath());
            return R.ok();
        }
        // 其他资源未找到的情况，记录warn日志
        log.warn("资源未找到: {}", e.getResourcePath());
        return R.no("资源不存在");
    }

    /**
     * 构建错误信息
     */
    private String buildErrorMessage(BindingResult result) {
        List<FieldError> fieldErrors = result.getFieldErrors();
        return fieldErrors.stream()
                .map(error -> String.format("%s: %s", error.getField(), error.getDefaultMessage()))
                .collect(Collectors.joining("; "));
    }
}
